package com.tico.common.service.impl;


import com.tico.common.mapper.BaseMapper;
import com.tico.common.service.BaseService;
import com.tico.common.utils.BaseQuery;
import com.tico.common.utils.QueryResult;
import com.tico.common.utils.SnowflakeIdWorker;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019-08-14.
 */
public abstract class AbstractService<T> implements BaseService<T> {

    protected SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 1);


    private BaseMapper<T> baseMapper;

    public void setBaseMapper(BaseMapper<T> baseMapper) {
        this.baseMapper = baseMapper;
    }

    @Override
    public T findById(Serializable id) {
        return baseMapper.findById(id);
    }

    @Override
    public int create(T obj) {
        return baseMapper.insert(obj);
    }

    @Override
    public int update(T obj) {
        return baseMapper.update(obj);
    }

    @Override
    public int remove(Serializable obj) {
        return baseMapper.remove(obj);
    }

    @Override
    public int delete(T obj) {
        return baseMapper.delete(obj);
    }

    @Override
    public int insertBatch(List<T> list) {
        return baseMapper.insertBatch(list);
    }

    @Override
    public List<T> findByNamedParamList(Map<String, Object> serializable) {
        return baseMapper.findByNamedParamList(serializable);
    }

    @Override
    public <E> QueryResult<E> findPageInfo(BaseQuery baseQuery) {
        QueryResult<E> result = new QueryResult<E>();
        result.setQuery(baseQuery);
        Map<String, Object> params = result.getQuery().build();
        Integer amount = baseMapper.countPageInfo(params);
        result.setTotalRecord(amount);
        if (amount == 0) {
            return result;
        }
        List<E> list = baseMapper.findPageInfo(params);
        if (!CollectionUtils.isEmpty(list)) {
            result.setResultList(list);
        }
        return result;
    }
}
